#include "attendancewidget.h"
#include "../../network/networkclient.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QCheckBox>
#include <QTableWidget>
#include <QHeaderView>
#include <QLineEdit>
#include <QComboBox>
#include <QDateEdit>
#include <QTextEdit>
#include <QMessageBox>
#include <QJsonArray>
#include <QStackedWidget>
#include <QFrame>

AttendanceWidget::AttendanceWidget(const Doctor& doctor, QWidget *parent)
    : QWidget(parent)
    , m_doctor(doctor)
    , m_isCheckedIn(false)
{
    setupUI();
    
    connect(&NetworkClient::instance(), &NetworkClient::messageReceived,
            this, &AttendanceWidget::onMessageReceived);
    
    updateTodayCheckInStatus();
}

AttendanceWidget::~AttendanceWidget()
{
}

void AttendanceWidget::setupUI()
{
    // 应用微信风格样式（医生端蓝色）
    this->setStyleSheet(R"(
        QWidget {
            background-color: #F7F7F7;
            color: #191919;
            font-family: "Microsoft YaHei UI", sans-serif;
        }
        
        QPushButton {
            background-color: #409EFF;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 8px 16px;
        }
        
        QPushButton:hover {
            background-color: #66B1FF;
        }
        
        QPushButton:pressed {
            background-color: #3A8EE6;
        }
        
        QPushButton:disabled {
            background-color: #D0D0D0;
            color: #909090;
        }
        
        QTableWidget {
            background-color: white;
            border: 1px solid #E0E0E0;
            border-radius: 6px;
            gridline-color: #F0F0F0;
        }
        
        QTableWidget::item {
            padding: 5px;
        }
        
        QTableWidget::item:selected {
            background-color: #E7F4FF;
            color: #191919;
        }
        
        QHeaderView::section {
            background-color: #FAFAFA;
            color: #191919;
            padding: 8px;
            border: none;
            border-bottom: 1px solid #E0E0E0;
            font-weight: bold;
        }
        
        QLineEdit, QTextEdit, QDateEdit, QComboBox {
            background-color: white;
            border: 1px solid #E0E0E0;
            border-radius: 4px;
            padding: 6px 10px;
            color: #191919;
        }
        
        QLineEdit:focus, QTextEdit:focus, QDateEdit:focus, QComboBox:focus {
            border-color: #409EFF;
        }
        
        QCheckBox {
            color: #191919;
        }
        
        QLabel {
            background-color: transparent;
            color: #191919;
        }
    )");
    
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    
    // 顶部按钮区域
    QHBoxLayout* topLayout = new QHBoxLayout();
    
    QPushButton* dailyBtn = new QPushButton("日常打卡");
    QPushButton* leaveBtn = new QPushButton("请假");
    QPushButton* cancelBtn = new QPushButton("销假");
    QPushButton* backBtn = new QPushButton("返回");
    
    dailyBtn->setMinimumHeight(40);
    leaveBtn->setMinimumHeight(40);
    cancelBtn->setMinimumHeight(40);
    backBtn->setMinimumHeight(40);
    
    connect(dailyBtn, &QPushButton::clicked, this, &AttendanceWidget::onDailyCheckInClicked);
    connect(leaveBtn, &QPushButton::clicked, this, &AttendanceWidget::onLeaveRequestClicked);
    connect(cancelBtn, &QPushButton::clicked, this, &AttendanceWidget::onCancelLeaveClicked);
    connect(backBtn, &QPushButton::clicked, this, &AttendanceWidget::onBackClicked);
    
    topLayout->addWidget(dailyBtn);
    topLayout->addWidget(leaveBtn);
    topLayout->addWidget(cancelBtn);
    topLayout->addStretch();
    topLayout->addWidget(backBtn);
    
    mainLayout->addLayout(topLayout);
    
    // 添加分隔线
    QFrame* line = new QFrame();
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    mainLayout->addWidget(line);
    
    // 创建堆叠widget
    m_stackedWidget = new QStackedWidget();
    
    setupDailyCheckInPage();
    setupLeaveRequestPage();
    setupCancelLeavePage();
    
    m_stackedWidget->addWidget(m_dailyCheckInPage);
    m_stackedWidget->addWidget(m_leaveRequestPage);
    m_stackedWidget->addWidget(m_cancelLeavePage);
    
    mainLayout->addWidget(m_stackedWidget);
    
    m_stackedWidget->setCurrentIndex(0);
}

void AttendanceWidget::setupDailyCheckInPage()
{
    m_dailyCheckInPage = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(m_dailyCheckInPage);
    
    // 今日打卡区域
    QHBoxLayout* checkInLayout = new QHBoxLayout();
    m_todayCheckBox = new QCheckBox("今日打卡");
    m_todayCheckBox->setStyleSheet("QCheckBox { font-size: 16px; font-weight: bold; }");
    connect(m_todayCheckBox, &QCheckBox::toggled, this, &AttendanceWidget::onTodayCheckBoxToggled);
    checkInLayout->addWidget(m_todayCheckBox);
    checkInLayout->addStretch();
    layout->addLayout(checkInLayout);
    
    // 历史打卡记录
    QLabel* historyLabel = new QLabel("历史打卡记录（近两年）");
    historyLabel->setStyleSheet("font-size: 14px; font-weight: bold; margin-top: 20px;");
    layout->addWidget(historyLabel);
    
    m_attendanceTable = new QTableWidget();
    m_attendanceTable->setColumnCount(3);
    m_attendanceTable->setHorizontalHeaderLabels({"日期", "打卡时间", "记录时间"});
    m_attendanceTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_attendanceTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_attendanceTable->horizontalHeader()->setStretchLastSection(true);
    layout->addWidget(m_attendanceTable);
}

void AttendanceWidget::setupLeaveRequestPage()
{
    m_leaveRequestPage = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(m_leaveRequestPage);
    layout->setSpacing(15);
    
    QLabel* titleLabel = new QLabel("请假申请");
    titleLabel->setStyleSheet("font-size: 18px; font-weight: bold;");
    layout->addWidget(titleLabel);
    
    // 手机号
    QHBoxLayout* phoneLayout = new QHBoxLayout();
    QLabel* phoneLabel = new QLabel("联系方式:");
    phoneLabel->setMinimumWidth(80);
    m_phoneEdit = new QLineEdit();
    m_phoneEdit->setPlaceholderText("11位手机号");
    m_phoneEdit->setMaxLength(11);
    phoneLayout->addWidget(phoneLabel);
    phoneLayout->addWidget(m_phoneEdit);
    layout->addLayout(phoneLayout);
    
    // 请假性质
    QHBoxLayout* typeLayout = new QHBoxLayout();
    QLabel* typeLabel = new QLabel("请假性质:");
    typeLabel->setMinimumWidth(80);
    m_leaveTypeCombo = new QComboBox();
    m_leaveTypeCombo->addItem("因公");
    m_leaveTypeCombo->addItem("因私");
    typeLayout->addWidget(typeLabel);
    typeLayout->addWidget(m_leaveTypeCombo);
    layout->addLayout(typeLayout);
    
    // 起始日期
    QHBoxLayout* startLayout = new QHBoxLayout();
    QLabel* startLabel = new QLabel("开始日期:");
    startLabel->setMinimumWidth(80);
    m_startDateEdit = new QDateEdit();
    m_startDateEdit->setCalendarPopup(true);
    m_startDateEdit->setDate(QDate::currentDate());
    startLayout->addWidget(startLabel);
    startLayout->addWidget(m_startDateEdit);
    layout->addLayout(startLayout);
    
    // 结束日期
    QHBoxLayout* endLayout = new QHBoxLayout();
    QLabel* endLabel = new QLabel("结束日期:");
    endLabel->setMinimumWidth(80);
    m_endDateEdit = new QDateEdit();
    m_endDateEdit->setCalendarPopup(true);
    m_endDateEdit->setDate(QDate::currentDate());
    endLayout->addWidget(endLabel);
    endLayout->addWidget(m_endDateEdit);
    layout->addLayout(endLayout);
    
    // 请假事由
    QLabel* reasonLabel = new QLabel("请假事由:");
    layout->addWidget(reasonLabel);
    m_reasonEdit = new QTextEdit();
    m_reasonEdit->setPlaceholderText("限制60字");
    m_reasonEdit->setMaximumHeight(100);
    layout->addWidget(m_reasonEdit);
    
    // 按钮
    QHBoxLayout* btnLayout = new QHBoxLayout();
    QPushButton* submitBtn = new QPushButton("提交");
    QPushButton* cancelBtn = new QPushButton("取消");
    submitBtn->setMinimumHeight(35);
    cancelBtn->setMinimumHeight(35);
    connect(submitBtn, &QPushButton::clicked, this, &AttendanceWidget::onSubmitLeaveClicked);
    connect(cancelBtn, &QPushButton::clicked, this, &AttendanceWidget::onCancelLeaveRequestClicked);
    btnLayout->addStretch();
    btnLayout->addWidget(submitBtn);
    btnLayout->addWidget(cancelBtn);
    layout->addLayout(btnLayout);
    
    layout->addStretch();
}

void AttendanceWidget::setupCancelLeavePage()
{
    m_cancelLeavePage = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(m_cancelLeavePage);
    
    QLabel* titleLabel = new QLabel("请假记录 - 点击进入详情进行销假");
    titleLabel->setStyleSheet("font-size: 16px; font-weight: bold;");
    layout->addWidget(titleLabel);
    
    m_leaveRecordsTable = new QTableWidget();
    m_leaveRecordsTable->setColumnCount(6);
    m_leaveRecordsTable->setHorizontalHeaderLabels({"性质", "开始日期", "结束日期", "事由", "状态", "ID"});
    m_leaveRecordsTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_leaveRecordsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_leaveRecordsTable->horizontalHeader()->setStretchLastSection(true);
    m_leaveRecordsTable->setColumnHidden(5, true);
    connect(m_leaveRecordsTable, &QTableWidget::cellDoubleClicked, this, &AttendanceWidget::onLeaveRecordClicked);
    layout->addWidget(m_leaveRecordsTable);
}

void AttendanceWidget::onDailyCheckInClicked()
{
    m_stackedWidget->setCurrentIndex(0);
    updateTodayCheckInStatus();
    loadAttendanceRecords();
}

void AttendanceWidget::onLeaveRequestClicked()
{
    m_stackedWidget->setCurrentIndex(1);
    m_phoneEdit->setText(m_doctor.phone);
}

void AttendanceWidget::onCancelLeaveClicked()
{
    m_stackedWidget->setCurrentIndex(2);
    
    QJsonObject request;
    request["doctor_id"] = m_doctor.id;
    NetworkClient::instance().sendRequest(MSG_GET_LEAVE_REQUESTS, request);
}

void AttendanceWidget::onBackClicked()
{
    emit backToMain();
}

void AttendanceWidget::onTodayCheckBoxToggled(bool checked)
{
    QJsonObject request;
    request["doctor_id"] = m_doctor.id;
    
    if (checked) {
        NetworkClient::instance().sendRequest(MSG_ATTENDANCE_CHECKIN, request);
    } else {
        request["date"] = QDate::currentDate().toString("yyyy-MM-dd");
        NetworkClient::instance().sendRequest(MSG_ATTENDANCE_CANCEL, request);
    }
}

void AttendanceWidget::updateTodayCheckInStatus()
{
    QJsonObject request;
    request["doctor_id"] = m_doctor.id;
    NetworkClient::instance().sendRequest(MSG_GET_TODAY_ATTENDANCE, request);
}

void AttendanceWidget::loadAttendanceRecords()
{
    QJsonObject request;
    request["doctor_id"] = m_doctor.id;
    request["start_date"] = QDate::currentDate().addYears(-2).toString("yyyy-MM-dd");
    request["end_date"] = QDate::currentDate().toString("yyyy-MM-dd");
    NetworkClient::instance().sendRequest(MSG_GET_ATTENDANCE_RECORDS, request);
}

void AttendanceWidget::onSubmitLeaveClicked()
{
    QString phone = m_phoneEdit->text().trimmed();
    if (phone.length() != 11) {
        QMessageBox::warning(this, "提示", "请输入11位手机号");
        return;
    }
    
    QString reason = m_reasonEdit->toPlainText().trimmed();
    if (reason.length() > 60) {
        QMessageBox::warning(this, "提示", "请假事由不能超过60字");
        return;
    }
    
    if (reason.isEmpty()) {
        QMessageBox::warning(this, "提示", "请填写请假事由");
        return;
    }
    
    if (m_startDateEdit->date() > m_endDateEdit->date()) {
        QMessageBox::warning(this, "提示", "开始日期不能晚于结束日期");
        return;
    }
    
    QJsonObject request;
    request["doctor_id"] = m_doctor.id;
    request["phone"] = phone;
    request["leave_type"] = m_leaveTypeCombo->currentText();
    request["start_date"] = m_startDateEdit->date().toString("yyyy-MM-dd");
    request["end_date"] = m_endDateEdit->date().toString("yyyy-MM-dd");
    request["reason"] = reason;
    // 不设置status，让服务端使用默认值"已批准"
    
    NetworkClient::instance().sendRequest(MSG_CREATE_LEAVE_REQUEST, request);
}

void AttendanceWidget::onCancelLeaveRequestClicked()
{
    QMessageBox::StandardButton reply = QMessageBox::question(
        this, "确认", "是否确认取消？",
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        m_phoneEdit->clear();
        m_reasonEdit->clear();
        m_startDateEdit->setDate(QDate::currentDate());
        m_endDateEdit->setDate(QDate::currentDate());
        m_leaveTypeCombo->setCurrentIndex(0);
        QMessageBox::information(this, "提示", "取消成功！");
    } else {
        QMessageBox::information(this, "提示", "即将返回请假界面......");
    }
}

void AttendanceWidget::onLeaveRecordClicked(int row)
{
    int requestId = m_leaveRecordsTable->item(row, 5)->text().toInt();
    QString status = m_leaveRecordsTable->item(row, 4)->text();
    
    if (status == "已销假") {
        QMessageBox::information(this, "提示", "该请假记录已销假");
        return;
    }
    
    QMessageBox::StandardButton reply = QMessageBox::question(
        this, "销假确认", "确认要销假吗？",
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        onCancelLeaveConfirm(requestId);
    }
}

void AttendanceWidget::onCancelLeaveConfirm(int requestId)
{
    QJsonObject request;
    request["request_id"] = requestId;
    NetworkClient::instance().sendRequest(MSG_CANCEL_LEAVE, request);
}

void AttendanceWidget::onMessageReceived(MessageType type, const QJsonObject& data)
{
    if (type == MSG_ATTENDANCE_CHECKIN_RESPONSE) {
        if (data["success"].toBool()) {
            m_isCheckedIn = true;
            QMessageBox::information(this, "成功", data["message"].toString());
            loadAttendanceRecords();
        } else {
            m_todayCheckBox->setChecked(false);
            QMessageBox::warning(this, "错误", data["error"].toString());
        }
    }
    else if (type == MSG_ATTENDANCE_CANCEL_RESPONSE) {
        if (data["success"].toBool()) {
            m_isCheckedIn = false;
            QMessageBox::information(this, "成功", data["message"].toString());
            loadAttendanceRecords();
        } else {
            m_todayCheckBox->setChecked(true);
            QMessageBox::warning(this, "错误", data["error"].toString());
        }
    }
    else if (type == MSG_GET_TODAY_ATTENDANCE_RESPONSE) {
        if (data["success"].toBool()) {
            bool hasAttendance = data["has_attendance"].toBool();
            m_todayCheckBox->blockSignals(true);
            m_todayCheckBox->setChecked(hasAttendance);
            m_todayCheckBox->blockSignals(false);
            m_isCheckedIn = hasAttendance;
            
            if (hasAttendance) {
                loadAttendanceRecords();
            }
        }
    }
    else if (type == MSG_GET_ATTENDANCE_RECORDS_RESPONSE) {
        if (data["success"].toBool()) {
            QJsonArray records = data["records"].toArray();
            m_attendanceTable->setRowCount(0);
            
            for (const QJsonValue& value : records) {
                QJsonObject record = value.toObject();
                int row = m_attendanceTable->rowCount();
                m_attendanceTable->insertRow(row);
                
                m_attendanceTable->setItem(row, 0, new QTableWidgetItem(record["attendance_date"].toString()));
                m_attendanceTable->setItem(row, 1, new QTableWidgetItem(record["attendance_time"].toString()));
                m_attendanceTable->setItem(row, 2, new QTableWidgetItem(record["create_time"].toString()));
            }
        }
    }
    else if (type == MSG_CREATE_LEAVE_REQUEST_RESPONSE) {
        if (data["success"].toBool()) {
            QString message = data["message"].toString();
            int canceledCount = data["canceled_count"].toInt();
            
            // 根据是否取消预约显示不同类型的提示
            if (canceledCount > 0) {
                QMessageBox::information(this, "成功", message);
            } else {
                QMessageBox::information(this, "成功", message);
            }
            
            m_phoneEdit->clear();
            m_reasonEdit->clear();
            m_startDateEdit->setDate(QDate::currentDate());
            m_endDateEdit->setDate(QDate::currentDate());
        } else {
            QMessageBox::warning(this, "错误", data["error"].toString());
        }
    }
    else if (type == MSG_GET_LEAVE_REQUESTS_RESPONSE) {
        if (data["success"].toBool()) {
            QJsonArray requests = data["requests"].toArray();
            m_leaveRecordsTable->setRowCount(0);
            
            for (const QJsonValue& value : requests) {
                QJsonObject request = value.toObject();
                int row = m_leaveRecordsTable->rowCount();
                m_leaveRecordsTable->insertRow(row);
                
                m_leaveRecordsTable->setItem(row, 0, new QTableWidgetItem(request["leave_type"].toString()));
                m_leaveRecordsTable->setItem(row, 1, new QTableWidgetItem(request["start_date"].toString()));
                m_leaveRecordsTable->setItem(row, 2, new QTableWidgetItem(request["end_date"].toString()));
                m_leaveRecordsTable->setItem(row, 3, new QTableWidgetItem(request["reason"].toString()));
                m_leaveRecordsTable->setItem(row, 4, new QTableWidgetItem(request["status"].toString()));
                m_leaveRecordsTable->setItem(row, 5, new QTableWidgetItem(QString::number(request["id"].toInt())));
            }
        }
    }
    else if (type == MSG_CANCEL_LEAVE_RESPONSE) {
        if (data["success"].toBool()) {
            QMessageBox::information(this, "成功", data["message"].toString());
            // 刷新列表
            QJsonObject request;
            request["doctor_id"] = m_doctor.id;
            NetworkClient::instance().sendRequest(MSG_GET_LEAVE_REQUESTS, request);
        } else {
            QMessageBox::warning(this, "错误", data["error"].toString());
        }
    }
}

